import re
from PyQt5.QtWidgets import QVBoxLayout, QComboBox, QHBoxLayout, QWidget, QTextEdit, QTableWidget, QPushButton, \
    QDoubleSpinBox, QLabel

from src.backend.api.topic import topic
from src.backend.tools.file import calculate_similarity
from src.forward.base.RightWidget import RightWidget
from src.forward.base.bean import forward, Table_ABC


@forward(name='资源仓库')
class TopicSelect(RightWidget):

    def __init__(self):
        super().__init__()

        self.topicselect_layout=QVBoxLayout(self)
        self.setLayout(self.topicselect_layout)
        # 查询div
        topic_select = QWidget()
        self.select_layout = QHBoxLayout()
        topic_select.setLayout(self.select_layout)

        self.type_class = QComboBox()
        self.type_class.addItems(['全部','单选', '多选', '填空', '解答','判断'])
        self.difficult_class = QComboBox()
        self.difficult_class.addItems(['全部','简单', '中档', '较难', '困难'])
        from src.forward.base.bean import CustomTextEdit
        from src.backend.beanfactory import BeanFactory
        path = BeanFactory.getCursor().image_path
        self.topic_edit = CustomTextEdit(path)
        self.topic_edit.setPlaceholderText('添加需要查询相似的题目')
        self.topic_edit.setFixedHeight(160)
        label=QLabel('文本相似度:')
        self.doubleSpinBox = QDoubleSpinBox(topic_select)
        self.doubleSpinBox.setRange(0.0, 1.0)
        self.doubleSpinBox.setSingleStep(0.01)
        self.doubleSpinBox.setDecimals(2)
        self.doubleSpinBox.setValue(0.5)  # 设置初始值为0.5

        push_class=QPushButton('查询')
        push_class.clicked.connect(self.query)

        self.select_layout.addWidget(self.type_class)
        self.select_layout.addWidget(self.difficult_class)
        self.select_layout.addWidget(self.topic_edit)
        self.select_layout.addWidget(label)
        self.select_layout.addWidget(self.doubleSpinBox)
        self.select_layout.addWidget(push_class)

        self.topic_table=Table_ABC()
        self.topic_table.setFixedHeight(400)

        self.topicselect_layout.addWidget(topic_select)
        self.topicselect_layout.addWidget(self.topic_table)

        self.query()
    def query(self):

        sim=self.doubleSpinBox.value()
        text=None
        if self.topic_edit.toPlainText():
            html = self.topic_edit.toHtml()
            from src.backend.tools.file import parser_html_to_strs
            content_list = parser_html_to_strs(html)
            if re.match(r'^\d+$', content_list[0]):
                text = ' '.join(content_list[2:])
            else:
                text = ' '.join(content_list[1:])
        type=self.type_class.currentIndex()+1
        level=self.difficult_class.currentIndex()+1
        results=topic(type,level)
        if len(results)>0:
            if text:
                results['sim']=results['资源内容'].apply(lambda x:calculate_similarity(text,x))
                results=results.loc[results['sim']>sim,:]
            self.topic_table.fill_data(results)



